package com.etrans.baf.analyse.task.alarm.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.etrans.baf.analyse.task.alarm.domain.AlarmInfo;
import com.etrans.baf.analyse.util.Constants;
import com.etrans.baf.analyse.util.DateUtils;
import com.etrans.baf.analyse.util.Sysconfig;
import com.etrans.baf.analyse.util.XmlReader;
import com.mongodb.BasicDBObject;
import com.mongodb.CommandResult;
import com.mongodb.DBObject;
@Service
public class AlarmService {
    @Autowired
	private MongoTemplate egovMongoTemplate;//引入配置的mongod模版
	static final Logger logger = LoggerFactory.getLogger(AlarmService.class);

	/**
	 * 实时报警和处警分析
	 * @throws Exception 
	 */
	public void alarmSwap() throws Exception{
		Date analyseDate = new Date();
 		String dirUrl=System.getProperty("analyse")+Sysconfig.getPropValueByCode("alarm");
    	String table_date= DateUtils.format(analyseDate, Constants.DATE_YYMMDD);
    	mapReduceAlarm(dirUrl, table_date);
    	mapReduceAlarmResult(dirUrl, DateUtils.format(analyseDate, Constants.DATE_YYYY_MM_DD));
	}
	/**
	 * 司机报警分析
	 * @throws Exception 
	 */
	public void driverAlarmSwap(String analyse_date)throws Exception{
  		String dirUrl=System.getProperty("analyse")+Sysconfig.getPropValueByCode("alarm");
  		driverAnalyse(dirUrl, analyse_date);
	}
	/**
	 * 热区报警分析
	 * @param analyse_date
	 */
	public void hotAlarmSwap(String analyse_date){
		String dirUrl=System.getProperty("analyse")+Sysconfig.getPropValueByCode("alarm");
  		try {
			hotAnalyse(dirUrl, analyse_date);
		} catch (Exception e) {
 			e.printStackTrace();
		}
	}
	/**
	 * 热区报警分析
	 * @param dirUrl
	 * @param analyse_date
	 * @throws Exception
	 */
	private void hotAnalyse(String dirUrl,String analyse_date)throws Exception{
		Map<String,String> map = XmlReader.readXmlToMapReduce(dirUrl+"vehicle_hot_swap_alarm.xml");
        if(map!=null && map.size()>0){
        	Date analyseDate = DateUtils.parse(analyse_date, Constants.DATE_YYYY_MM_DD);
        	String table_date = DateUtils.format(analyseDate,Constants.DATE_YYMMDD);
        	DBObject command = new BasicDBObject();
        	DBObject sort = new BasicDBObject();
        	sort.put("_id",1); 
        	DBObject query = new BasicDBObject();
        	DBObject coordinates = new BasicDBObject();coordinates.put("$exists", true);
            query.put("coordinates", coordinates);
           	command.put("mapreduce","alarm_info_"+table_date);
        	command.put("query", query);
         	command.put("map",map.get("map"));
        	command.put("reduce",map.get("reduce"));
        	command.put("finalize",map.get("finalize"));
        	command.put("out","vehicle_hot_swap_alarm"); 
        	command.put("sort", sort);//analyse_date
        	CommandResult result = egovMongoTemplate.executeCommand(command);
        	boolean ok = result.ok();
        	logger.info("热区报警分析vehicle_hot_swap_alarm"+(ok?"成功":"失败：原因"+result.getErrorMessage()));
        	if(ok){
        		Query rquery = Query.query(Criteria.where("analyse_date").is(analyseDate));
            	int dcount = egovMongoTemplate.remove(rquery,"hot_alarm_swap").getN();
            	logger.info("热区报警分析删除已经分析的 hot_alarm_swap表"+dcount);
            	String last_date = DateUtils.getAnalyseDate(analyse_date,-1);//mongodb小时
             	String update = map.get("update").replaceAll("DATE_YYMMDD", table_date).replaceAll("DATE_YYYY_MM_DD",last_date);
        		egovMongoTemplate.getDb().doEval(update);//追加
        	}
        }
	}

	/**
	 * 司机报警分析
	 * @param dirUrl
	 * @param analyse_date
	 * @throws Exception
	 */
	private void driverAnalyse(String dirUrl,String analyse_date)throws Exception{
		Map<String,String> map = XmlReader.readXmlToMapReduce(dirUrl+"vehicle_driver_swap_alarm.xml");
        if(map!=null && map.size()>0){
        	Date analyseDate = DateUtils.parse(analyse_date, Constants.DATE_YYYY_MM_DD);
        	String table_date = DateUtils.format(analyseDate,Constants.DATE_YYMMDD);
        	DBObject command = new BasicDBObject();
        	DBObject sort = new BasicDBObject();
        	sort.put("_id",1);
        	DBObject query = new BasicDBObject();
        	DBObject licence = new BasicDBObject();licence.put("$exists", true);
        	DBObject driverName = new BasicDBObject();driverName.put("$exists", true);
            query.put("licence", licence);
            query.put("driverName", driverName);
          	command.put("mapreduce","alarm_info_"+table_date);
        	command.put("query", query);
        	command.put("map",map.get("map"));
        	command.put("reduce",map.get("reduce"));
        	command.put("finalize",map.get("finalize"));
        	command.put("out","vehicle_driver_swap_alarm"); 
        	command.put("sort", sort);//analyse_date
        	CommandResult result = egovMongoTemplate.executeCommand(command);
        	boolean ok = result.ok();
        	logger.info("司机报警分析vehicle_driver_swap_alarm"+(ok?"成功":"失败：原因"+result.getErrorMessage()));
        	if(ok){
        		Query rquery = Query.query(Criteria.where("analyse_date").is(analyseDate));
            	int dcount = egovMongoTemplate.remove(rquery,"driver_alarm_swap").getN();
            	logger.info("司机报警分析删除已经分析的 driver_alarm_swap表"+dcount);
            	String last_date = DateUtils.getAnalyseDate(analyse_date,-1);//mongodb小时
             	String update = map.get("update").replaceAll("DATE_YYMMDD", table_date).replaceAll("DATE_YYYY_MM_DD",last_date);
        		egovMongoTemplate.getDb().doEval(update);//追加
	      
        	}

        }
	}
	/**
     * 实时报警分析
     * @param dirUrl 文件目录地址
     * @param table_date yyMMdd
     * @throws Exception
     */
	private void mapReduceAlarm(String dirUrl,String table_date) throws Exception{
		Map<String,String> exp = XmlReader.readXmlToMapReduce(dirUrl+"alarm_swap.xml");
         if(exp!=null&& exp.size()>0){
         	DBObject command = new BasicDBObject();
        	DBObject sort = new BasicDBObject();
        	sort.put("_id",1);
         	command.put("mapreduce","alarm_info_"+table_date);
        	command.put("map",exp.get("map"));
        	command.put("reduce",exp.get("reduce"));
        	command.put("finalize",exp.get("finalize"));
        	command.put("out","alarm_swap"); 
        	command.put("sort", sort);//analyse_date
        	CommandResult result = egovMongoTemplate.executeCommand(command);
        	boolean ok = result.ok();
            logger.info("创建alarm_swap"+(ok?"成功":"失败:"+result.getErrorMessage()));
 	        
         }
    }
	/**
     * 实时处警分析
     * @param dirUrl 文件目录地址
     * @param analyse_date yyyy-MM-dd
     * @throws Exception
     */
	private void mapReduceAlarmResult(String dirUrl,String analyse_date) throws Exception{
		Map<String,String> exp = XmlReader.readXmlToMapReduce(dirUrl+"alarm_swap_result.xml");
         if(exp!=null&& exp.size()>0){
         	DBObject command = new BasicDBObject();
        	DBObject sort = new BasicDBObject();
        	sort.put("_id",1);
        	DBObject query = new BasicDBObject();
        	DBObject time = new BasicDBObject();
        	time.put("$gte",DateUtils.parse(analyse_date+" 00:00:00.000"));
        	time.put("$lte",DateUtils.parse(analyse_date+" 23:59:59.999"));
        	DBObject final_result =new BasicDBObject();
        	final_result.put("$exists",true);
        	query.put("final_result",final_result);
        	DBObject info_id=new BasicDBObject();
        	info_id.put("$exists",true);//查询存在列的数据
        	query.put("info_id", info_id);
        	query.put("alarm_time", time);
         	command.put("mapreduce","alarm_result");
        	command.put("query", query);
        	command.put("map",exp.get("map"));
        	command.put("reduce",exp.get("reduce"));
        	command.put("finalize",exp.get("finalize"));
        	command.put("out","alarm_swap_result"); 
        	command.put("sort", sort);//analyse_date
        	CommandResult result = egovMongoTemplate.executeCommand(command);
        	boolean ok = result.ok();
            logger.info("创建alarm_swap_result"+(ok?"成功":"失败:"+result.getErrorMessage()));
 	        
         }
    }

 
	
}
